package com.zhaoqi.hr.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务
 */
@Service
public class SmsService {

    private static final Logger log = LoggerFactory.getLogger(SmsService.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${sms.access-key-id}")
    private String accessKeyId;

    @Value("${sms.access-key-secret}")
    private String accessKeySecret;

    @Value("${sms.sign-name}")
    private String signName;

    @Value("${sms.template-code}")
    private String templateCode;

    private static final String SMS_CODE_PREFIX = "sms:code:";
    private static final int CODE_EXPIRE_MINUTES = 5;
    private static final int CODE_LENGTH = 6;

    /**
     * 发送验证码
     */
    public void sendVerificationCode(String phone) {
        // 生成6位随机验证码
        String code = generateCode();
        
        // 存储验证码到Redis，5分钟过期
        String key = SMS_CODE_PREFIX + phone;
        redisTemplate.opsForValue().set(key, code, CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);
        
        // 发送短信（这里使用模拟发送，实际项目中需要对接真实的短信服务商）
        sendSms(phone, code);
        
        log.info("验证码已发送到手机号: {}, 验证码: {}", phone, code);
    }

    /**
     * 验证验证码
     */
    public boolean verifyCode(String phone, String code) {
        String key = SMS_CODE_PREFIX + phone;
        String storedCode = redisTemplate.opsForValue().get(key);
        
        if (storedCode == null) {
            log.warn("验证码不存在或已过期: {}", phone);
            return false;
        }
        
        boolean isValid = storedCode.equals(code);
        if (isValid) {
            // 验证成功后删除验证码
            redisTemplate.delete(key);
            log.info("验证码验证成功: {}", phone);
        } else {
            log.warn("验证码验证失败: {}, 输入: {}, 期望: {}", phone, code, storedCode);
        }
        
        return isValid;
    }

    /**
     * 生成随机验证码
     */
    private String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 发送短信（模拟实现）
     * 实际项目中需要对接阿里云短信、腾讯云短信等服务商
     */
    private void sendSms(String phone, String code) {
        // 模拟发送短信
        log.info("模拟发送短信 - 手机号: {}, 验证码: {}, 签名: {}, 模板: {}", 
                phone, code, signName, templateCode);
        
        // 实际实现示例（阿里云短信）：
        /*
        try {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            IAcsClient client = new DefaultAcsClient(profile);
            
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phone);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            
            SendSmsResponse response = client.getAcsResponse(request);
            if (!"OK".equals(response.getCode())) {
                throw new RuntimeException("短信发送失败: " + response.getMessage());
            }
        } catch (Exception e) {
            log.error("短信发送异常", e);
            throw new RuntimeException("短信发送失败");
        }
        */
    }
}
